﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;

namespace ASoft.WPF
{
    public class FileImageSource : AnimatedImageSource
    {
        public FileImageSource(string directoryPath)
        {
            DirectoryInfo di = new DirectoryInfo(directoryPath);
            var images = di.GetFiles().Select(p =>
                {
                    var bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.UriSource = new Uri(p.FullName);
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.EndInit();
                    return bitmapImage;
                })
                .ToList();
            Load(images);
        }

        void Load(List<BitmapImage> images)
        {
            frames = images.Select(source =>
                {
                    BitmapDecoder decoder = null;
                    
                    if (source.StreamSource != null)
                    {
                        decoder = BitmapDecoder.Create(source.StreamSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
                    }
                    else if (source.UriSource != null)
                    {
                        decoder = BitmapDecoder.Create(source.UriSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
                    }

                    if (decoder != null && decoder.Frames.Count == 1)
                    {
                        //decoder.Frames[0].Freeze();
                        return decoder.Frames[0];
                    }
                    return null;
                })
                .Where(source => source != null)
                .ToList();
        }

        List<BitmapFrame> frames;
        public override List<BitmapFrame> Frames
        {
            get { return frames; }
        }
    }
}
